require "utils.package"

require "moaix.app"
require "moaix.input"
require "moaix.physics"
require "moaix.resources"
require "utils.euclid"

require "glutton.config"

resource = moaix.resources.ResourceFinder:new()
print(resource:add_path("../res/fonts"))
print(resource:add_path("../res/images"))
print(resource:add_path("../res/physics"))

function onCollide(event, fixtureA, fixtureB, arbiter)
    if event == MOAIBox2DArbiter.BEGIN then print('begin!')
    elseif event == MOAIBox2DArbiter.END then print('end!')
    elseif event == MOAIBox2DArbiter.PRE_SOLVE then print('pre!')
    elseif event == MOAIBox2DArbiter.POST_SOLVE then print('post!') end
end

mouse = moaix.input.mouse
mouse.on_mouse_left_press(function(...)
    print(...)
    local x0, y0 = body:getWorldCenter()
    local x1, y1 = App.layer.default:wndToWorld(mouse.x, mouse.y)
    local a = utils.euclid.angle(x0, y0, x1, y1)
    body:applyLinearImpulse(math.cos(a), math.sin(a))
end)


App = moaix.app
App.init(glutton.config)
App.add_viewport(10, 0)
App.add_layer(App.viewport.default)

App.add_viewport(App.config.width, -App.config.height, "hud"):setOffset(-1, 1)
App.add_layer(App.viewport.hud, "hud")

-- camera = App.add_camera(App.layer.default)

-- mouse_textbox = mouse.debug_textbox(0, 0, 300, 300)
-- mouse_textbox:setYFlip(false)
-- App.layer.hud:insertProp(mouse_textbox)

-- require "moaix.misc"
-- fps_textbox = moaix.misc.fps_textbox(600, 0, 800, 300)
-- fps_textbox:setYFlip(false)
-- fps_textbox:setAlignment(MOAITextBox.RIGHT_JUSTIFY)
-- App.layer.hud:insertProp(fps_textbox)

-- fps_textbox = moaix.misc.fps_textbox(0.8, 0, 1, 0.2)
-- fps_textbox:setYFlip(false)
-- fps_textbox:setAlignment(MOAITextBox.RIGHT_JUSTIFY)
-- App.add_ui_viewport("foo")
-- App.add_layer(App.viewport.foo, "foo")
-- App.layer.foo:insertProp(fps_textbox)


-- set up the world and start its simulation
Physics = moaix.physics
Physics.create_world()

body = Physics.read_json(resource:find("test.json"), MOAIBox2DBody.DYNAMIC)[1]
body:setFixedRotation(true)
body:setTransform(0, 2)

Physics.set_body.density(body, 1)
Physics.set_body.filter(body, 0x01)
Physics.set_body.friction(body, 0.3)
Physics.set_body.collision_handler(body, onCollide, 
                                   MOAIBox2DArbiter.BEGIN + MOAIBox2DArbiter.END, 0x02)
body:resetMassData()
body:applyAngularImpulse(0.2)
body:applyLinearImpulse(0, 2)

body2 = Physics.world:addBody(MOAIBox2DBody.STATIC)
body2:setTransform(0, -3, 60)
fixture2 = body2:addRect(-2, -1, 2, 1)
fixture2:setFilter(0x02)
fixture2:setCollisionHandler(onCollide, MOAIBox2DArbiter.BEGIN + MOAIBox2DArbiter.END
+ MOAIBox2DArbiter.PRE_SOLVE + MOAIBox2DArbiter.POST_SOLVE, 0x00)

-- debug draw physics world in default layer and start the simulation
App.layer.default:setBox2DWorld(Physics.world)  
Physics.world:start()
